import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { List, Skeleton, message } from 'antd'
import moment from 'moment'
import { MoreOutlined, FileTextOutlined, FileDoneOutlined, UserOutlined, BellOutlined } from '@ant-design/icons'
import Calendar from '@components/Calendar'
import style from './BusinessDesktop.module.less'
import { updateUncompleteMessage } from '@redux/actions'

class BusinessDesktop extends Component {
  state = {
    year: moment().year(),
    month: moment().month(),
    day: moment().format('YYYY-MM-DD'),
    dateList: [],
    courtList: [],
    dealingCaseNumber: 0,
    dealingCaseNumberLoading: false,
    toCourtNumber: 0,
    toCourtNumberLoading: false,
    willTimeoutNumber: 0,
    willTimeoutNumberLoading: false,
    timeoutNumber: 0,
    timeoutNumberLoading: false,
    arbWillTimeoutNumber: 0,
    arbWillTimeoutNumberLoading: false,
    arbTimeoutNumber: 0,
    arbTimeoutNumberLoading: false,
    loading: false,
    statisticLoading: false
  }

  formatDate (date) {
    if (!date) { return date }
    return moment(date * 1000).format('YYYY-MM-DD HH:mm')
  }

  toDealHandle (d) {
    this.setState({ messageListvisible: false })
    let route = d.route ? d.route : null
    if (!route) {
      return message.warning('处理地址不存在')
    }
    try {
      route = JSON.parse(route)
    } catch (e) {
      return message.warning('获取处理地址错误')
    }
    const component = route.component || route.type
    if (component === 'caseDetail') {
      const { id, operate } = route.meta
      this.props.addWindow({ id: `CaseDetail-${id}`, title: `案件详情-${route.title}`, componentName: 'CaseDetail', forceRefresh: false, meta: { id, operate, editable: true } })
    }
    this.setMessageReaded(d.read_datetime, d.id)
  }

  // 设置未读信息未已读
  setMessageReaded (time, id) {
    if (time) { return false }
    this.$put(`/api/xapc/message/read/${id}`)
      .then(res => {
        if (res.status === 1) {
          this.props.updateUncompleteMessage()
        } else {
          message.warning(res.message)
        }
      })
  }

  openMessageList () {
    this.setState({ messageListvisible: false })
    this.props.addWindow({ id: 'MessageList', title: '消息列表', componentName: 'MessageList' })
  }

  // 获取开庭信息
  getCourtList () {
    this.setState({ loading: true })
    this.$get('/api/xapc/hearingroombook/day', {
      day: this.state.day,
      operatorid: this.props.userInfo.id
    }).then(res => {
      this.setState({ loading: false })
      if (res.status === 1) {
        this.setState({
          courtList: res.data
        })
      } else {
        message.warning(res.message)
      }
    }).catch(() => this.setState({ loading: false }))
  }

  getTime (d) {
    if (!d) {
      return d
    }
    return moment(d * 1000).format('HH:mm')
  }

  formatArbitrator (d) {
    const list = [d.arbitrator]
    if (d.arbitrator1) {
      list.push(d.arbitrator1)
      list.push(d.arbitrator2)
    }
    return list.join('、')
  }

  // 获取在办案件数
  getDealingCaseNumber () {
    this.setState({ dealingCaseNumberLoading: true })
    const { id } = this.props.userInfo
    return this.$get('/api/xapc/case', {
      condition: JSON.stringify([{ k: 'status', o: 'in', v: '移交办案,送达完成,已组庭,已结案' }, { k: 'operatorid', o: '=', v: id }]
      ),
      conly: true
    }).then(res => {
      this.setState({ dealingCaseNumberLoading: false })
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      this.setState({
        dealingCaseNumber: res.data
      })
    }).catch(() => this.setState({ dealingCaseNumberLoading: false }))
  }

  // 获取待组庭案件数
  getToCourtNumber () {
    this.setState({ toCourtNumberLoading: true })
    const { id } = this.props.userInfo
    return this.$get('/api/xapc/case', {
      condition: JSON.stringify([{ k: 'status', o: 'in', v: '移交办案,送达完成' }, { k: 'operatorid', o: '=', v: id }]
      ),
      conly: true
    }).then(res => {
      this.setState({ toCourtNumberLoading: false })
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      this.setState({
        toCourtNumber: res.data
      })
    }).catch(() => this.setState({ toCourtNumberLoading: false }))
  }

  // 获取预警数量
  getStatisNum (type, degree, numKey) {
    this.setState({ [`${numKey}Loading`]: true })
    return this.$get('/api/xapc/casestat/limitStat', {
      conly: 1,
      type,
      degree,
      statusex: '在办',
      condition: JSON.stringify([{ k: 'operatorid', o: '=', v: this.props.userInfo.id }])
    }).then(res => {
      this.setState({ [`${numKey}Loading`]: false })
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      this.setState({
        [numKey]: res.data
      })
    }).catch(() => this.setState({ [`${numKey}Loading`]: false }))
  }

  // 获取即将延期案件数
  getWillTimeoutNumber (numKey) {
    return this.getStatisNum('trial_limit', 'warning', numKey)
  }

  // 获取延期案件数
  getTimeoutNumber (numKey) {
    return this.getStatisNum('trial_limit', 'over', numKey)
  }

  // 获取组庭即将延期案件数
  getArbWillTimeoutNumber (numKey) {
    return this.getStatisNum('arbitrator_sel_limit', 'warning', numKey)
  }

  // 获取组庭延期案件数
  getArbTimeoutNumber (numKey) {
    return this.getStatisNum('arbitrator_sel_limit', 'over', numKey)
  }

  // 获取统计数据
  getStatistics () {
    this.getDealingCaseNumber()
    this.getToCourtNumber()
    this.getWillTimeoutNumber('willTimeoutNumber')
    this.getTimeoutNumber('timeoutNumber')
    this.getArbWillTimeoutNumber('arbWillTimeoutNumber')
    this.getArbTimeoutNumber('arbTimeoutNumber')
  }

  // 前往在办案件
  gotoDealing () {
    this.props.addWindow({ id: 'MyCase', title: '我的案件', componentName: 'MyCase', forceRefresh: true, meta: { status: '在办' } })
  }

  // 前往待组庭案件
  gotoCourt () {
    this.props.addWindow({ id: 'MyCase', title: '我的案件', componentName: 'MyCase', forceRefresh: true, meta: { status: '送达完成' } })
  }

  // 前往我的预警
  toMyWarningCase (activeType) {
    this.props.addWindow({ id: 'MyWarningCase', title: '我的案件预警', componentName: 'MyWarningCase', meta: { activeType } })
  }

  // 前往即将延期
  gotoWillTimeout () {
    this.toMyWarningCase('延期审限')
  }

  // 前往延期
  gotoTimeout () {
    this.toMyWarningCase('已延期审限')
  }

  // 前往组庭即将延期
  gotoArbWillTimeout () {
    this.toMyWarningCase('即将延期组庭')
  }

  // 前往组庭延期
  gotoArbTimeout () {
    this.toMyWarningCase('已延期组庭')
  }

  // 设置年份与月份
  setMonthAndYear (d) {
    const m = moment(d)
    const year = m.year()
    const month = m.month()
    if (this.state.year === year && this.state.month === month) {
      return false
    }
    this.setState({
      year: m.year(),
      month: m.month()
    }, () => {
      this.getMonthCourtDate(year, month)
    })
  }

  // 格式化数据为两位数
  formatDouble (num) {
    return num < 10 ? `0${num}` : num
  }

  // 获取月份内的开庭日期
  getMonthCourtDate (year, month) {
    month = this.formatDouble(month + 1)
    const m = moment(`${year}-${month}-01 00:00:00`)
    const begintime = Math.floor(m.valueOf() / 1000)
    m.add(1, 'month')
    m.subtract(1, 'd')
    const endtime = Math.floor(moment(`${m.format('YYYY-MM-DD')} 23:59:59`) / 1000)
    this.$get('/api/xapc/hearingroombook/datecount', {
      begintime,
      endtime,
      operatorid: this.props.userInfo.id
    }).then(res => {
      if (res.status === 1) {
        const dateList = res.data.map(li => li.date)
        this.setState({
          dateList
        })
      } else {
        message.warning(res.message)
      }
    })
  }

  changeDate (day) {
    this.setState({ day }, () => this.getCourtList())
    this.setMonthAndYear(day)
  }

  componentDidMount () {
    this.getMonthCourtDate(this.state.year, this.state.month)
    this.getCourtList()
    this.getStatistics()
  }

  // 渲染提醒块
  renderNoticeItem (title, numKey, icon, activeStyle, handle = () => {}) {
    const num = this.state[numKey]
    if (this.state[`${numKey}Loading`]) {
      return (
        <div className={style['header-block']}>
          <Skeleton active />
        </div>
      )
    }
    const blockStyle = [style['header-block']]
    if (num > 0) {
      blockStyle.push(activeStyle)
    }
    return (
      <div className={blockStyle.join(' ')} onClick={() => handle()}>
        <div className={style['icon-box']}>
          {icon}
        </div>
        <div className={style['header-block-text']}>
          <div className={style['header-block__text--top']}>{title}</div>
          <div className={style['header-block__text--bottom']}>
            <span className={style['header-block__text-num']}>{num}</span>
            <span className={style['header-block__text-unit']}>件</span>
          </div>
        </div>
      </div>
    )
  }

  // 渲染提示列表
  renderNoticeItemList () {
    return (
      <>
        {this.renderNoticeItem('在办案件', 'dealingCaseNumber', <FileTextOutlined />, style.active, () => this.gotoDealing())}
        {this.renderNoticeItem('待组庭', 'toCourtNumber', <UserOutlined />, style.active, () => this.gotoCourt())}
        {this.renderNoticeItem('组庭预警', 'arbWillTimeoutNumber', <FileTextOutlined />, style.warn, () => this.gotoArbWillTimeout())}
        {this.renderNoticeItem('超期组庭', 'arbTimeoutNumber', <BellOutlined />, style.error, () => this.gotoArbTimeout())}
        {this.renderNoticeItem('审限预警', 'willTimeoutNumber', <FileDoneOutlined />, style.warn, () => this.gotoWillTimeout())}
        {this.renderNoticeItem('超审限', 'timeoutNumber', <BellOutlined />, style.error, () => this.gotoTimeout())}
      </>
    )
  }

  // 渲染消息标题
  renderMessageTitle (item, i) {
    return (
      <span className={style['item-name']} onClick={() => this.toDealHandle(item)}>
        <span>{i + 1}、{item.title}</span>
        {item.level ? <span className={style['item-urgency']}>紧急</span> : null}
      </span>
    )
  }

  render () {
    return (
      <div className={style.container}>{/*  */}
        <div className={style.header}>
          <div className={style['header-inner']}>
            {this.renderNoticeItemList()}
          </div>
        </div>
        <div className={style.body}>
          <div className={style['body-left']}>
            <div className={style['body-title-line']}>
              <span className={style['body-title__text']}>提醒通知</span>
              <span className={style['body__more-btn']} onClick={() => this.openMessageList()}>
                <MoreOutlined rotate='90' />
              </span>
            </div>

            <div>
              <List
                itemLayout='horizontal' dataSource={this.props.uncompleteMessageList} pagination={false} renderItem={(item, i) => {
                  return (
                    <List.Item>
                      <Skeleton avatar title={false} loading={item.loading} active>
                        <List.Item.Meta
                          title={this.renderMessageTitle(item, i)}
                          description={item.content}
                        />
                        <span>{this.formatDate(item.create_datetime)}</span>
                      </Skeleton>
                    </List.Item>
                  )
                }}
              />
            </div>
          </div>
          <div className={style['body-right']}>
            <Calendar changeHandle={s => this.changeDate(s)} tagList={this.state.dateList} />
            <div className={style['book-list']}>
              <List
                dataSource={this.state.courtList} split={false} loading={this.state.loading} renderItem={li => {
                  return (
                    <List.Item key={li.id}>
                      <div className={style['book-li']}>
                        <span className={style['book-li__time']}>{this.getTime(li.begin_datetime)}</span>
                        <span>{li.caseno_desc} 案件在{li.name}{li.hearingroom_remark}{li.use}，办案秘书：{li.operator}，仲裁员：{this.formatArbitrator(li)}</span>
                      </div>
                    </List.Item>
                  )
                }}
              />
            </div>

            {/* {this.state.courtList.length === 0 ? <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /> : null}
            <ul className={style['book-list']}>
              {this.state.courtList.map(li => {
                return (
                  <li key={li.id}>
                    <span className={style['book-li__time']}>{this.getTime(li.begin_datetime)}</span>
                    <span>{li.caseno_desc} 案件在{li.name}开庭，仲裁员：{this.formatArbitrator(li)}</span>
                  </li>
                )
              })}
            </ul> */}
          </div>
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo,
    uncompleteMessageList: state.basic.uncompleteMessageList
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    updateUncompleteMessage: () => dispatch(updateUncompleteMessage(dispatch))
  }
})

export default connect(mapState, mapDispatch)(BusinessDesktop)
